package com.ldy.core.common;

import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ldy.core.entity.BaseMenu;
import com.ldy.core.service.BaseMenuService;
import com.ldy.core.util.MenuConfigUtil;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 菜单加载处理
 */
@Component
public class MenuLoadConfig {

	private static final Logger logger = LoggerFactory.getLogger(MenuLoadConfig.class);
	
	@Value("${app.id:}")
	private String appId;
	
	@Autowired
	private BaseMenuService menuService;
	
	@PostConstruct
	public void init () {
		try {			
			logger.info("=====加载菜单=====");
			if (StringUtils.isEmpty(appId)) {
				return;
			}
			List<BaseMenu> list = MenuConfigUtil.get();
			if (CollectionUtil.isNotEmpty(list)) {		
				QueryWrapper<BaseMenu> query = new QueryWrapper<>();
				query.eq("app_id", appId);
				menuService.remove(query);
				list.forEach(c -> {
					c.setAppId(appId);
					c.setId(appId + c.getId());
					if (c.getParentId() != null) {
						c.setParentId(appId + c.getParentId());
					}
				});
				menuService.saveBatch(list);
			}
		}catch (Exception e) {
			logger.error("", e);
		}
	}
}
